package org.jim.server.command.handler.extend;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.exception.ImException;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.command.handler.extend.pojo.UserOfGroup;
import org.jim.server.processor.group.GroupCmdProcessor;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 指定从组中删除用户
 * @author admin
 *
 */
public class ExitGroupReqHandler extends AbstractCmdHandler {
	
	private static Logger log = LoggerFactory.getLogger(ExitGroupReqHandler.class);
	
	@Override
	public ImPacket handler(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
		RespBody respBody = new RespBody(Command.COMMAND_EXIT_GROUP_RESP,ImStatus.C2002);
		//反馈的信息
		UserOfGroup group = JsonKit.toBean(packet.getBody(),UserOfGroup.class);
		if (StringUtils.isBlank(group.getGroupId())) {
			log.error("group is null,{}", imChannelContext);
			//JimServerAPI.close(imChannelContext, "group is null when operation");
			respBody.setMsg("群组不存在");
			ImPacket respPacket = ProtocolManager.Converter.respPacket(respBody, imChannelContext);
			return respPacket;
		}
//		if (StringUtils.isBlank(group.getUserIds())) {
//			log.error("userId  is null,{}", imChannelContext);
//			JimServerAPI.close(imChannelContext, "userId is null when operation");
//			return null;
//		}
		//如果有额外业务
		GroupCmdProcessor groupProcessor = this.getSingleProcessor(GroupCmdProcessor.class);
		if(Objects.nonNull(groupProcessor)){
			respBody = groupProcessor.removeUser(group.getGroupId(),group.getUserIds(),group.getType(), imChannelContext);
			
			boolean status = Objects.isNull(respBody);
			if (status) {
				respBody  = new RespBody(Command.COMMAND_EXIT_GROUP_RESP, ImStatus.C2002);
			}
			ImPacket respPacket = ProtocolManager.Converter.respPacket(respBody, imChannelContext);
			//respPacket.setStatus(ImStatus.C2002);
			return respPacket;
		}
		ImPacket respPacket = ProtocolManager.Converter.respPacket(respBody, imChannelContext);
		return respPacket;
	}
	@Override
	public Command command() {
		
		return Command.COMMAND_EXIT_GROUP_REQ;
	}
}
